package cn.superchart.web.core.handler;

import cn.hutool.json.JSONUtil;
import cn.superchart.common.base.BaseResult;
import cn.superchart.common.enums.ExceptionEnum;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 处理 已认证用户但权限不足 的异常（例如，已登录用户试图访问需要更高权限的资源）。 访问受阻的资源没有权限时触发
 */
@Component
public class ScAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        BaseResult<String> resResult = BaseResult.by(ExceptionEnum.AUTH_NOT_LEGAL,null);
        response.getWriter().write(JSONUtil.toJsonStr(resResult));
    }
}
